package selection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

import model.Chromosome;

public class RankSelection implements Selection {
	Random rand=new Random();
	@Override
	public Chromosome[] selectPatents(ArrayList<Chromosome> population) {
		Collections.sort(population, new Comparator<Chromosome>() {

			@Override
			public int compare(Chromosome o1, Chromosome o2) {
//				System.out.println(o1.getFitness()+"::"+o2.getFitness());
				if(o1==o2)
					return 0;
//				if(o1.getFitness()>o2.getFitness())
//					return 1;
//				else if(o2.getFitness()>o1.getFitness())
//					return -1;
//				else return 0;
//				return (int)(o1.getFitness()-o2.getFitness());
				return Double.compare(o1.getFitness(), o2.getFitness());
						
				
			}
		});
		int i=0;
		int sum=0;
		for (Chromosome chromosome : population) {
			sum+=i;
			chromosome.setExpVal(i++);
		}
		double flag=rand.nextDouble();
		double sum2=0;
		Chromosome parent1=null;
		for (Chromosome chromosome : population) {
			sum2+=chromosome.getExpVal()/sum;
			if(flag<sum2)
			{
				parent1 = chromosome;
				break;
			}
		}
		flag=rand.nextDouble();
		sum2=0;
		Chromosome parent2=null;
		for (Chromosome chromosome : population) {
			sum2+=chromosome.getExpVal()/sum;
			if(flag<sum2)
			{
				parent2 = chromosome;
				break;
			}
		}
		
		return new Chromosome[] {parent1,parent2};
	}
	@Override
	public String toString() {
		return "RankSelection";
	}

}
